using System;
using System.Collections.Generic;
using System.Text;

namespace Dida
{
	public class CollisionSoup
	{
		List<CollisionTriangle> triangles;
		Box bbox;

		public CollisionSoup()
		{
			bbox = Box.NullBox;
			triangles = new List<CollisionTriangle>();
		}

		public CollisionSoup(CollisionTriangle[] triangles)
		{
			this.triangles = new List<CollisionTriangle>(triangles);
			CalcBBox();
		}

		public void AddTriangle(CollisionTriangle tri)
		{
			bbox.Union(tri.BoundingBox);
		}

		private void CalcBBox()
		{
			bbox = Box.NullBox;
			foreach (CollisionTriangle tri in triangles)
				bbox.Union(tri.BoundingBox);
		}

		public bool TestForCollision(Sphere sphere, Vector3D dir,
			out CollisionResult res)
		{
			res = null;
			bool collision = false;
			foreach (CollisionTriangle tri in triangles)
			{
				CollisionResult curRes;
				if (tri.TestForCollision(sphere, dir, out curRes))
				{
					if (res == null || curRes.dist < res.dist)
					{
						res = curRes;
						collision = true;
					}
				}
			}

			return collision;
		}

		public Box BoundingBox
		{
			get { return bbox; }
		}

		public void DrawDebug(IGeometryDebugDraw target)
		{
			foreach (CollisionTriangle tri in triangles)
				tri.DrawDebug(target,0x0000ff00);
		}
	}
}
